package com.goodrain.oauth2demo.controller;

import com.google.gson.Gson;
import okhttp3.*;

import java.util.HashMap;
import java.util.Map;

public class Config {
    private String clientID;
    private String clientSecret;
    private String[] scopes;
    private String redirectURL;
    private String authServerURL;
    private Endpoint endpoint;

    public Config(String clientID, String clientSecret, String[] scopes, String redirectURL, String authServerURL, String authURL, String tokenURL) {
        this.clientID = clientID;
        this.clientSecret = clientSecret;
        this.scopes = scopes;
        this.redirectURL = redirectURL;
        this.authServerURL = authServerURL;
        this.endpoint = new Endpoint(authURL, tokenURL);
    }

    public String AuthCodeURL(String state) {
        HttpUrl.Builder builder = new HttpUrl.Builder()
                .addQueryParameter("client_id", clientID)
                .addQueryParameter("scopes", String.join(" ", scopes))
                .addQueryParameter("redirect_uri", redirectURL)
                .addQueryParameter("response_type", "code")
                .addQueryParameter("state", state);
        String url = endpoint.authURL + builder.toString();
        return url.replace("///", "/");
    }

    public String retrieveToken(String code) throws Exception {
        String url = endpoint.tokenURL;

        Map<String, String> map = new HashMap<>();
        map.put("grant_type", "authorization_code");
        map.put("code", code);
        map.put("client_id", clientID);
        map.put("client_secret", clientSecret);
        if (!redirectURL.isEmpty()) {
            map.put("redirect_uri", redirectURL);
        }
        Gson gson = new Gson();
        FormBody.Builder builder = new FormBody.Builder()
                .add("grant_type", "authorization_code")
                .add("code", code)
                .add("client_id", clientID)
                .add("client_secret", clientSecret);
        if (!redirectURL.isEmpty()) {
            builder.add("redirect_uri", redirectURL);
        }
        FormBody formBody = builder.build();

        Request request = new Request.Builder()
                .addHeader("ContentType", "application/x-www-form-urlencoded")
                .post(formBody)
                .url(url)
                .build();

        System.out.println(request.toString());

        OkHttpClient client = new OkHttpClient();
        Response response = client.newCall(request).execute();
        if (response.code() != 200) {
            throw new Exception(response.message());
        }
        return response.body().string();
    }
}


